package com.sk.bilibili.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sk.bilibili.other.R;
import org.springframework.stereotype.Service;

import java.util.regex.Pattern;

import org.springframework.beans.factory.annotation.Autowired;
import com.sk.bilibili.bean.Cover;
import com.sk.bilibili.mapper.CoverMapper;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author 邵康
 * @date 2021/12/10 00:13
 */
@Service
public class CoverService extends ServiceImpl<CoverMapper, Cover> {

    @Autowired
    private MinioService minioService;
    private static final String COVER_PATH = "cover/cover/%s.jpg";
    private static final Pattern COVER_PATTERN = Pattern.compile("/(cover/cover/.*jpg)");

    public R<Void> add(Cover cover) {
        cover.setCover(minioService.add(cover.getCoverFile(), COVER_PATH));
        save(cover);
        return R.success();
    }

    public R<Void> delete(Integer id) {
        Cover temp = getById(id);
        minioService.delete(temp.getCover(), COVER_PATTERN);
        removeById(id);
        return R.success();
    }

    public R<Void> update(Cover cover) {
        Cover temp = getById(cover.getId());
        String coverUrl = minioService.update(COVER_PATH, COVER_PATTERN, temp.getCover(), cover.getCoverFile());
        cover.setCover(coverUrl);
        updateById(cover);
        return R.success();
    }

    public R<IPage<Cover>> page(Integer page, Integer size) {
        return R.success(page(new Page<>(page, size), null));
    }

    public R<Cover> getCover(Integer id) {
        return R.success(getById(id));
    }

}
